try:
    from pyecharts import options as opts
    from pyecharts.charts import WordCloud
except ImportError:  # pragma: no cover - optional dependency for visualizations
    WordCloud = None
    opts = None

try:
    import jieba
except ImportError:  # pragma: no cover - optional dependency for visualizations
    jieba = None
from .models import Product

def build_wordcloud():
    # 从数据库中获取所有产品数据
    products = Product.objects.all()
    
    # 提取电商产品名称
    names = [product.name for product in products]
    
    # 如果没有产品数据，使用默认数据
    if not names:
        names = ['电商产品', '推荐系统', '数据分析', '用户体验', '商品推荐']

    # 将电商产品名称拼接为字符串
    text = ' '.join(names)

    if jieba:
        # 使用jieba进行中文分词
        seg_list = jieba.cut(text)
        seg_text = ' '.join(seg_list)
    else:
        seg_text = text

    # 统计词频
    words = seg_text.split()
    word_counts = {}
    for word in words:
        if word not in word_counts:
            word_counts[word] = 0
        word_counts[word] += 1

    if WordCloud and opts:
        # 创建词云图
        wordcloud = (
            WordCloud()
                .add("", list(word_counts.items()), word_size_range=[20, 150])
                .set_global_opts(title_opts=opts.TitleOpts(title="电商产品名称词云图"))
        )

        # 生成词云图并保存
        wordcloud.render("static/product_wordcloud.html")
    else:
        # 如果依赖缺失，写入一个简单的文本文件作为占位
        placeholder_path = "static/product_wordcloud.html"
        with open(placeholder_path, 'w', encoding='utf-8') as placeholder:
            placeholder.write('<h3>词云功能依赖 pyecharts/jieba，当前环境未安装相关包。</h3>')
